package com.dtkavin.threads.syn;

import java.util.Random;
import java.util.concurrent.Exchanger;
import java.util.concurrent.ThreadFactory;

/**
 * Created by john on 10/4/16.
 * 两个线程交换数据，只限2个线程！！
 */
public class ExchangerDemo {

    public static void main(String[] args) {
        final Exchanger exchanger = new Exchanger();

        new Thread(new Runnable() {
            public void run() {
                try {
                    String data = "aaa-1";
                    System.out.println(Thread.currentThread().getName() + " ： " + data);
                    Thread.sleep(new Random().nextInt(5000));
                    Object exchange = exchanger.exchange(data);
                    System.out.println(Thread.currentThread().getName() + " : exchanged: " + exchange.toString());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        new Thread(new Runnable() {
            public void run() {
                try {
                    String data = "bbb-2";
                    System.out.println(Thread.currentThread().getName() + " ： " + data);
                    Thread.sleep(new Random().nextInt(5000));
                    Object exchange = exchanger.exchange(data);
                    System.out.println(Thread.currentThread().getName() + " : exchanged: " + exchange.toString());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

}
